package servlets;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

public class chatroomServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ServletContext context = getServletContext();
        String mes = (String) context.getAttribute("chatroom");
        out.print(Objects.requireNonNullElse(mes, "false"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String message = request.getParameter("message");
        ServletContext context = getServletContext();
        String info = (String) context.getAttribute("chatroom");
        if (info == null)
            info = "";
        String chatmessage = info + "<span class='chatbubble'>" + username + "：" + message + "</span><br/>";
        System.out.println(chatmessage);
        context.setAttribute("chatroom", chatmessage); //存入键值对，或也叫属性名，和值
        //request.getRequestDispatcher("./blank.jsp").forward(request,response);
    }
}
